package com.thde.sdkdemo;

import android.app.Activity;
import android.content.Intent;
import android.content.res.Configuration;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.game.yxyl.BuildConfig;
import com.game.yxyl.R;
import com.thrsdk.DYFusionSDK;
import com.thrsdk.listener.IExitListener;
import com.thrsdk.listener.IListener;
import com.thrsdk.listener.InitListener;
import com.thrsdk.listener.SDKListenerInfo;
import com.thrsdk.listener.UserListenerInfo;
import com.thrsdk.log.LogUtils;
import com.thrsdk.model.data.PayInfo;
import com.thrsdk.model.data.RoleInfo;
import com.thrsdk.model.protocol.bean.CustomerBean;
import com.thrsdk.model.protocol.bean.LoginMessage;
import com.thrsdk.model.protocol.bean.ResCertificate;
import com.thrsdk.model.protocol.bean.ShareBean;

import org.json.JSONObject;

public class MainActivity extends Activity implements View.OnClickListener {
    public final static String TAG = "thrsdk";

    public Button mBtnlogin;
    public Button mBtninfo;
    public Button mBtnpay;
    public Button mBtnperson;
    public Button mBtnexit;
    public Button mBtnswa;
    public Button btn_channlenum;//渠道标识
    public Button btn_paltformnum;//平台标识

    public Button btn_usercenter;
    private String appid = BuildConfig.appid;
    private String appkey = BuildConfig.appkey;
    public EditText edt_pay;
    public EditText edt_product;

    public Button btn_share;
    public Button btn_getcurrcycode;
    public Button btn_custom;
    public EditText edt_custom;
    public Button third_loginbt;
    public Button btn_eventreport;

    @Override
    protected void onStart() {
        super.onStart();
        DYFusionSDK.getInstance().onStart(this);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        String getChannelNumber = DYFusionSDK.getInstance().getChannelNumber(this);
        String getPlatformNumber = DYFusionSDK.getInstance().getPlatformNumber(this);

        Log.e("ChannelPlatmNumber", getChannelNumber + getPlatformNumber);

        setContentView(R.layout.activity_dyfusion_main);
        DYFusionSDK.getInstance().onCreate(this);
        initView();
        DYFusionSDK.getInstance().setUserListener(new UserListenerInfo() {
            @Override
            public void onLogout(Object obj) {
                // 账号退出成功.
                LogUtils.getInstance().d("账号退出成功。游戏方回到初始界面，重新登录");
                // 切换账号，处理自己的逻辑，比如重新登录，进行选服进入游戏
                Toast toast = Toast.makeText(MainActivity.this, "当前账号已退出，请重新登录", Toast.LENGTH_SHORT);
                toast.setGravity(Gravity.CENTER_VERTICAL, 0, 0);//竖直居中
                toast.show();
            }

        });
    }

    private void initView() {
        // TODO Auto-generated method stub
        mBtnlogin = (Button) findViewById(R.id.loginbt);
        mBtninfo = (Button) findViewById(R.id.dy_demo_info);
        mBtnpay = (Button) findViewById(R.id.paybt);
        mBtnperson = (Button) findViewById(R.id.personbt);
        mBtnexit = (Button) findViewById(R.id.exitbt);
        mBtnswa = (Button) findViewById(R.id.swabt);
        btn_usercenter = (Button) findViewById(R.id.btn_usercenter);

        btn_channlenum = (Button) findViewById(R.id.btn_channlenum);
        btn_paltformnum = (Button) findViewById(R.id.btn_paltformnum);
        edt_pay = (EditText) findViewById(R.id.edt_pay);
        edt_pay.clearFocus();

        edt_product = (EditText) findViewById(R.id.edt_product);
        edt_product.clearFocus();


        third_loginbt = (Button) findViewById(R.id.third_loginbt);
        btn_share = (Button) findViewById(R.id.btn_share);
        btn_getcurrcycode = (Button) findViewById(R.id.btn_getcurrcycode);
        btn_custom = (Button) findViewById(R.id.btn_custom);
        edt_custom = (EditText) findViewById(R.id.edt_custom);

        btn_eventreport = (Button) findViewById(R.id.btn_eventreport);

        third_loginbt.setOnClickListener(this);
        btn_share.setOnClickListener(this);
        btn_getcurrcycode.setOnClickListener(this);
        btn_custom.setOnClickListener(this);
        btn_eventreport.setOnClickListener(this);
        btn_channlenum.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String channelNumber = DYFusionSDK.getInstance().getChannelNumber(MainActivity.this);

                if (!TextUtils.isEmpty(channelNumber)) {
                    btn_channlenum.setText("渠道标识:" + channelNumber);
                }
            }
        });
        btn_paltformnum.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String PlatformNumber = DYFusionSDK.getInstance().getPlatformNumber(MainActivity.this);
                if (!TextUtils.isEmpty(PlatformNumber)) {
                    btn_paltformnum.setText("平台标识:" + PlatformNumber);
                }
            }
        });


        mBtnlogin.setOnClickListener(this);
        mBtninfo.setOnClickListener(this);
        mBtnpay.setOnClickListener(this);
        mBtnperson.setOnClickListener(this);
        mBtnexit.setOnClickListener(this);
        mBtnswa.setOnClickListener(this);
        btn_usercenter.setOnClickListener(this);

        // 初始化
        DYFusionSDK.getInstance().initInterface(MainActivity.this, appid, appkey,
                new InitListener() {

                    @Override
                    public void fail(String msg) {
                        // TODO Auto-generated method stub
                        Log.i(TAG, msg + ",请求失败,cp请注意");
                    }


                    @Override
                    public void Success(String msg) {
                        // TODO Auto-generated method stub
                        Toast.makeText(MainActivity.this, "初始化成功！：" + msg, Toast.LENGTH_SHORT).show();
                        Log.i(TAG, "初始化成功" + msg);
                    }
                });
    }

    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.loginbt) {
            // 登录
            DYFusionSDK.getInstance().login(MainActivity.this, new IListener<LoginMessage>() {

                @Override
                public void onSuccess(LoginMessage data) {
                    Log.i(TAG, "---------登录的---------");
                    if (data != null) {
                        Toast.makeText(MainActivity.this, "登录成功！" + data.getOpenId(), Toast.LENGTH_SHORT).show();
                        String gametoken = data.getToken();
                        String openId = data.getOpenId();

                    }
                }

                @Override
                public void onFail(String msg) {
                    Toast.makeText(MainActivity.this, "登陆失败！", Toast.LENGTH_SHORT).show();
                }
            });
        } else if (v == third_loginbt) {
            // TODO: 2023-05-12 第三方登录  
            DYFusionSDK.getInstance().onThirdCenter(MainActivity.this, new IListener<LoginMessage>() {
                @Override
                public void onSuccess(LoginMessage data) {

                }

                @Override
                public void onFail(String msg) {

                }
            });
        } else if (v.getId() == R.id.dy_demo_info) {
            /**
             * 额外信息
             *
             * @param context
             *            上下文
             * @param scene_Id
             *            场景 分别为进入服务器(enterServer)、玩家创建用户角色(createRole)、玩家升级(levelUp)
             * @param roleId
             *            角色id
             * @param roleName
             *            角色名
             * @param roleLevel
             *            角色等级
             * @param zoneId
             *            当前登录的游戏区服id
             * @param zoneName
             *            当前游戏区服名称
             * @param balance
             *            游戏币余额
             * @param Vip
             *            当前用户vip等级
             * @param partyName
             *            当前用户所属帮派
             */
            RoleInfo roleData = new RoleInfo();
            roleData.setScene_Id(RoleInfo.ENTER);
            roleData.setRoleid("11");
            roleData.setRolename("王者");
            roleData.setRolelevel("100");
            roleData.setZoneid("1");
            roleData.setZonename("1区");
            roleData.setBalance("80");
            roleData.setVip("8");
            roleData.setPartyname("逍遥");
            DYFusionSDK.getInstance().setExtData(this, roleData);

        } else if (v.getId() == R.id.paybt) {
            String paycost = edt_pay.getText().toString().trim();
            if (TextUtils.isEmpty(paycost) || !(Integer.parseInt(paycost) % 100 == 0)) {
                Toast.makeText(MainActivity.this, "请输入100的整数倍金额，单位分", Toast.LENGTH_SHORT).show();
                return;
            }

            PayInfo payInfo = new PayInfo();
            payInfo.setAmount(paycost);
            payInfo.setOrderid(System.currentTimeMillis() + "");
            payInfo.setExtrainfo(System.currentTimeMillis() + "");
            payInfo.setProductName("元宝");
            payInfo.setRoleid("11");
            payInfo.setRolename("王者");
            payInfo.setRolelevel("100");
            payInfo.setServerid("1");
            payInfo.setServername("1区");//服务器名称
            payInfo.setProductid("com.zhuguang.ceshi_2");//可选，商品计费点ID

            String product_id = edt_product.getText().toString().trim();
            if (!TextUtils.isEmpty(product_id)) {
                payInfo.setProductid(product_id);//可选，商品计费点ID
            }
            DYFusionSDK.getInstance().payment(this, payInfo, new SDKListenerInfo() {

                @Override
                public void onSuccess(Object obj) {
                    // TODO Auto-generated method stub
                    Log.i(TAG, "---------充值的--------------");
                    if (obj != null) {
                        Log.i(TAG, "充值界面成功" + obj.toString());
                        Toast.makeText(MainActivity.this, "充值界面成功", Toast.LENGTH_SHORT).show();

                    }
                }

                @Override
                public void onFail(String msg) {
                    Toast.makeText(MainActivity.this, "充值界面关闭" + msg, Toast.LENGTH_SHORT).show();
                }
            });

        } else if (v.getId() == R.id.personbt) {
            DYFusionSDK.getInstance().getCertificateData(this, new IListener<ResCertificate>() {
                @Override
                public void onSuccess(ResCertificate data) {

                    //获取到的认证信息,CP需要对认证信息自行处理
                    boolean result = data.getResult();//  认证结果
                    if (result) {
                        boolean isRealname = data.isRealname();//是否已实名
                        boolean isAdult = data.isAdult();//是否成年人
                        int age = data.getAge();//获取年龄信息 防沉迷年龄阶段分布【8至15周岁，16至18周岁，18以上是已成年】

                        Toast.makeText(MainActivity.this, "取到认证信息内容:" + data.toString(), Toast.LENGTH_LONG).show();

                    } else {
                        //未获取到认证信息
                        String unknownMessage = data.getMsg();
                        Toast.makeText(MainActivity.this, "未获取到认证信息内容:" + unknownMessage, Toast.LENGTH_LONG).show();
                    }


                }

                @Override
                public void onFail(String msg) {
                    //只返回Exception 不携带认证信息

                }
            });

        } else if (v.getId() == R.id.exitbt) {
            quitGame();
        } else if (v.getId() == R.id.swabt) {
            DYFusionSDK.getInstance().switchAccount();
        } else if (v.getId() == R.id.btn_usercenter) {
            DYFusionSDK.getInstance().onMainUserCenter(MainActivity.this);
        } else if (v == btn_share) {
            ShareBean shareBean = new ShareBean();
            shareBean.setName("游戏分享主题");
            shareBean.setDescribe("游戏分享详情");
            shareBean.setRoleid(System.currentTimeMillis() + "");
            DYFusionSDK.getInstance().onShare(MainActivity.this, shareBean, new IListener<String>() {
                @Override
                public void onSuccess(String data) {
                    if (!TextUtils.isEmpty(data)) {
                        Toast.makeText(MainActivity.this, "获取到分享连接:" + data.toString(), Toast.LENGTH_LONG).show();
                    }
                }

                @Override
                public void onFail(String msg) {

                }
            });
        } else if (v == btn_custom) {
            String str_edt_custom = edt_custom.getText().toString().trim();
            CustomerBean customerBean = new CustomerBean();
            customerBean.setDescribe(str_edt_custom);
            if (TextUtils.isEmpty(str_edt_custom)) {
                customerBean.setDescribe(CustomerBean.HOME);
            }
            DYFusionSDK.getInstance().onCustomerService(MainActivity.this, customerBean);

        } else if (v == btn_getcurrcycode) {
            String product_id = edt_product.getText().toString().trim();
            if (TextUtils.isEmpty(product_id)) {
                product_id = "com.zhuguang.ceshi_1";//可选，商品计费点ID
            }
            DYFusionSDK.getInstance().onGetPriceCurrencySuccess(MainActivity.this, product_id, new IListener<String>() {
                @Override
                public void onSuccess(String data) {
                    if (null != data) {
                        Toast.makeText(MainActivity.this, "获取到货币单位符号:" + data, Toast.LENGTH_LONG).show();
                    }
                }

                @Override
                public void onFail(String msg) {
                }
            });
        } else if (v == btn_eventreport) {
            try {

                String eventName = "level_achieved";
                JSONObject object = new JSONObject();
                object.put("level", "1");
                String jsonkeyvaue = object.toString();
                DYFusionSDK.getInstance().onEventReport(MainActivity.this, eventName, jsonkeyvaue);

            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    private void quitGame() {
        DYFusionSDK.getInstance().exit(MainActivity.this, new IExitListener() {
            @Override
            public void exitSuccess(String msg) {
                MainActivity.this.finish();
                System.exit(0);
            }

            @Override
            public void fail(String msg) {
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        // TODO Auto-generated method stub
        super.onActivityResult(requestCode, resultCode, data);
        DYFusionSDK.getInstance().onActivityResult(MainActivity.this, requestCode, resultCode, data);
    }

    @Override
    protected void onDestroy() {
        // TODO Auto-generated method stub
        super.onDestroy();
        DYFusionSDK.getInstance().onDestroy(this);
    }

    @Override
    protected void onPause() {
        // TODO Auto-generated method stub
        super.onPause();
        DYFusionSDK.getInstance().onPause(this);
    }

    @Override
    protected void onRestart() {
        // TODO Auto-generated method stub
        super.onRestart();
        DYFusionSDK.getInstance().onRestart(this);
    }

    @Override
    protected void onResume() {
        // TODO Auto-generated method stub
        super.onResume();
        DYFusionSDK.getInstance().onResume(this);
    }

    @Override
    protected void onStop() {
        // TODO Auto-generated method stub
        super.onStop();
        DYFusionSDK.getInstance().onStop(this);
    }

    @Override
    protected void onNewIntent(Intent intent) {
        // TODO Auto-generated method stub
        super.onNewIntent(intent);
        DYFusionSDK.getInstance().onNewIntent(intent);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        DYFusionSDK.getInstance().onKeyDown(keyCode, event);
        return super.onKeyDown(keyCode, event);
    }

    // TODO: 必接 退出游戏
    @Override
    public void onBackPressed() {
        quitGame();
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        DYFusionSDK.getInstance().onConfigurationChanged(newConfig);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        DYFusionSDK.getInstance().onRequestPermissionsResult(requestCode, permissions, grantResults);
    }


}
